<?php


namespace app\community\oauth2\Model;


use app\cms\community\lib\QueryModel;
use app\community\oauth2\Exception\ClientUserInvalidException;
use iflow\Response;
use League\OAuth2\Server\Entities\AuthCodeEntityInterface;

class oauthUserAccessCodeModel extends QueryModel
{
    protected $table = 'oauth_user_access_code_table';

    /**
     * 验证是否过期
     * @param string $codeId
     * @param string $app_id
     * @param string $open_id
     * @return bool
     * @throws ClientUserInvalidException
     */
    public function hasAccessCode(string $codeId, string $app_id, string $open_id): bool
    {
        // TODO: 验证当前Code是否有效
        $code = $this->findInfo([
            'code' => $codeId,
            'app_id' => request() -> params('client_id')
        ]);

        if (!$code) {
            throw new ClientUserInvalidException('Invalid Access Code');
        }

        if ($code['expired'] < time()) {
            throw new ClientUserInvalidException('AccessCode has expired');
        }

        return false;
    }

    /**
     * 将Code写入数据库
     * @param AuthCodeEntityInterface $authCode
     * @return Response
     */
    public function saveAccessCode(AuthCodeEntityInterface $authCode): Response
    {
        return $this->createData([
            'app_id' => $authCode -> getClient() -> getIdentifier(),
            'code' => $authCode -> getIdentifier(),
            'expired' => $authCode -> getExpiryDateTime() -> getTimestamp(),
            'user_code' => $authCode -> getUserIdentifier()
        ]);
    }
}